﻿using Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Polly;
using Polly.Timeout;

namespace PollyDemo
{
    public class ProductServices
    {

        Random random = new Random();

        public List<Product> GetList()
        {
            var retryPolly = Policy.Handle<TimeoutRejectedException>().Retry(3, (ex, count) =>
            {
                Common.LogHelper.Error($"第{count}次错误，错误信息：{ex.Message}");
                Common.LogHelper.Info($"，错误位置{ex.Source}");
            });

            var timeOutPolly = Policy.Timeout(TimeSpan.FromSeconds(1), TimeoutStrategy.Pessimistic);

            var mainPolly = retryPolly.Wrap(timeOutPolly);

            return mainPolly.Execute(() =>
                {
                    Common.LogHelper.Info("正在执行--Execute--");

                    Thread.Sleep(random.Next(0, 1001));

                    return AllList();
                });


        }


        private List<Product> AllList()
        {

            return new List<Product> {
            new Product{Id=random.Next(1,9999),Name="我是一个产品"+random.Next(99,99999),Price=random.Next(1,500),  },
            new Product{Id=random.Next(1,9999),Name="我是一个产品"+random.Next(99,99999),Price=random.Next(1,500),  },
            new Product{Id=random.Next(1,9999),Name="我是一个产品"+random.Next(99,99999),Price=random.Next(1,500),  },
            new Product{Id=random.Next(1,9999),Name="我是一个产品"+random.Next(99,99999),Price=random.Next(1,500),  },
            new Product{Id=random.Next(1,9999),Name="我是一个产品"+random.Next(99,99999),Price=random.Next(1,500),  },
        };


        }

        
    }
}
